import React, { Component } from 'react';
import { Modal, List, Avatar, Input, message } from 'antd';
import axios from 'axios';
import dayjs from 'dayjs';
import './index.css';

const TextArea = Input.TextArea;

export default class CommentModal extends Component {
  state = {
    visible: false,
    commentVal: '',
    dataList: [],
    total: 0
  }
  getList = (records) => {
    axios.get(`http://localhost:8000/comment/get?articleId=${records._id}`).then(res => {
      const data = res.data || {};
      this.setState({
        dataList: data.dataList || [],
        total: data.total
      })
    })
  }
  show = (records) => {
    this.records = records;
    this.setState({
      visible: true
    }, () => {
      this.getList(records);
    })
  }
  hide = () => {
    this.setState({
      visible: false,
      commentVal: ''
    })
  }
  handleInput = (e) => {
    const value = e.target.value || '';
    this.setState({
      commentVal: value
    })
  }
  handleOk = () => {
    axios.post('http://localhost:8000/comment/add', {
      articleId: this.records._id,
      commentVal: this.state.commentVal
    }).then(res => {
      const data = res.data || {};
      if (data && data.success) {
        message.success(data.msg);
        this.getList(this.records);
        this.setState({
          commentVal: ''
        })
      }
    })
  }
  render() {
    const { visible, commentVal, dataList, total } = this.state;
    const titleEle = ({ index, item }) => (
      <div>
        <big style={{marginRight: 20}}>#{index + 1}楼</big>
        <small>{dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')}</small>
      </div>
    )
    return (
      <Modal
        className="comment-modal"
        width={700}
        title={`评论列表（${total}条）`}
        visible={visible}
        okText="确定"
        cancelText="取消"
        onCancel={this.hide}
        footer={null}
      > 
        <div className="list-box">
          <List
            itemLayout="horizontal"
            dataSource={dataList}
            renderItem={(item, index) => (
              <List.Item>
                <List.Item.Meta
                  avatar={<Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" />}
                  title={titleEle({index, item})}
                  description={item.commentVal}
                />
              </List.Item>
            )}
          />
        </div>
        <div>
          <TextArea
            rows={5}
            onPressEnter={this.handleOk}
            onChange={this.handleInput.bind(this)}
            value={commentVal}
            placeholder='请说出你的看法...，按回车键提交'
          />
        </div>
      </Modal>
    )
  }
}
